package com.h5ve.toolkit.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.h5ve.toolkit.entity.GroupInfo;
import com.h5ve.toolkit.mapper.GroupInfoMapper;
import com.h5ve.toolkit.service.GroupInfoService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 分组表 服务实现类
 * </p>
 *
 * @author h5ve
 * @since 2019-01-30
 */
@Service
@AllArgsConstructor
public class GroupInfoServiceImpl extends ServiceImpl<GroupInfoMapper, GroupInfo> implements GroupInfoService {

    /**
     * 构建树
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<GroupInfo> buildTree(List<GroupInfo> list, int parentId) {
        List<GroupInfo> groupList = new ArrayList<>();
        Iterator<GroupInfo> iterator;
        for (iterator = list.iterator(); iterator.hasNext(); ) {
            GroupInfo t = iterator.next();
            if (t.getParentId() == parentId) {
                recursion(list, t);
                groupList.add(t);
            }
        }
        groupList.sort(Comparator.comparingInt(GroupInfo::getSort));
        return groupList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursion(List<GroupInfo> list, GroupInfo t) {
        // 得到子节点列表
        List<GroupInfo> childList = getChildList(list, t);
        t.setChildren(childList);
        for (GroupInfo tChild : childList) {
            if (hasChild(list, tChild)) {
                // 判断是否有子节点
                for (GroupInfo n : childList) {
                    recursion(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<GroupInfo> getChildList(List<GroupInfo> list, GroupInfo t) {
        List<GroupInfo> tlist = new ArrayList<>();
        for (GroupInfo n : list) {
            if (n.getParentId().intValue() == t.getId().intValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<GroupInfo> list, GroupInfo t) {
        return getChildList(list, t).size() > 0;
    }

}
